#!/bin/sh /etc/rc.common
# Copyright (C) 2019 Dengfeng Liu

START=99

USE_PROCD=1
NAME=kcptun-c
PROG=/usr/bin/${NAME}

validate_section_kcptun() 
{
	uci_load_validate "${NAME}" kcptun "$1" "$2" \
		'local_port:port' \
		'remote_ip:string' \
		'remote_port:port' \
		'mode:string' \
		'nocomp:bool' \
		'sndwnd:uinteger' \
		'rcvwnd:uinteger' \
		'disabled:bool'
}

kcptun_instance() 
{
	[ "$2" = 0 ] || {
		echo "validation failed"
		return 1
	}

	[ "${disabled}" = "1" ] && return 1

	[ "${local_port}" -gt 0 ] && [ "${local_port}" -lt 65536 ] || return 1

	[ "${remote_port}" -gt 0 ] && [ "${remote_port}" -lt 65536 ] || return 1

	[ -n "${remote_ip}" ] || {
		return 1
	}

	procd_open_instance
	procd_set_param command "${PROG}"
	procd_append_param command --localaddr ":${local_port}"
	procd_append_param command --remoteaddr "${remote_ip}:${remote_port}"
	[ -n "${mode}" ] && procd_append_param command --mode "${mode}"
	[ "${nocomp}" -eq 1 ] && procd_append_param command --nocomp
	[ "${sndwnd}" -gt 0 ] && procd_append_param command --sndwnd "${sndwnd}"
	[ "${rcvwnd}" -gt 0 ] && procd_append_param command --rcvwnd "${rcvwnd}"
	procd_set_param respawn
	procd_close_instance
}

start_service() 
{
	config_load "${NAME}"
	config_foreach validate_section_kcptun kcptun kcptun_instance
}
